﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Swift.Math;

public class UIMgr : MonoBehaviour {

    public static RectTransform crt;
    public static Camera cam;

    public Transform Arrow;
    
    private void Awake()
    {
        var canvas = GetComponentInChildren<Canvas>();
        crt = canvas.GetComponent<RectTransform>();
        cam = canvas.GetComponent<Camera>();
    }

    public static Vector2 GetScreenPosByWorldPos(Vector3 wp)
    {
        var vp = Camera.main.WorldToViewportPoint(wp);
        return new Vector2(crt.rect.width * vp.x, crt.rect.height * vp.y);
    }

    public static void SetUIByWorldPos(RectTransform rt, Vector3 wp)
    {
        var sp = GetScreenPosByWorldPos(wp);
        rt.anchoredPosition = new Vector2((float)sp.x, (float)sp.y);
    }

    public void ShowArrow(bool visible, Vector2 from, Vector2 to, bool canUse)
    {
        RectTransformUtility.ScreenPointToLocalPointInRectangle(crt, from, cam, out from);
        RectTransformUtility.ScreenPointToLocalPointInRectangle(crt, to, cam, out to);

        Arrow.GetComponent<Image>().color = canUse ? Color.red : Color.gray;
        Arrow.gameObject.SetActive(visible);
        Arrow.GetComponent<RectTransform>().localPosition = (from + to) / 2;
        var d = to - from;
        Arrow.localRotation = Quaternion.AngleAxis((float)MathEx.Dir(new Vec2(d.x, d.y)), Vector3.forward);
        Arrow.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, d.magnitude);
    }

    public Monster CheckTarget(Vector2 sp)
    {
        var ray = Camera.main.ScreenPointToRay(sp);
        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo))
        {
            var m = hitInfo.collider.GetComponent<Monster>();
            return m;
        }

        return null;
    }
}
